<template>
  <div class="account-management">
    <el-card class="search-card">
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="账户号">
            <el-input v-model="searchForm.accountNo" placeholder="请输入账户号" clearable />
          </el-form-item>
          <el-form-item label="开户人">
            <el-input v-model="searchForm.accountName" placeholder="请输入开户人姓名" clearable />
          </el-form-item>
          <el-form-item label="账户类型">
            <el-select v-model="searchForm.accountType" placeholder="请选择账户类型" clearable style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="个人账户" value="1" />
              <el-option label="企业账户" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="账户状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="正常" value="1" />
              <el-option label="冻结" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序方式">
            <el-select v-model="searchForm.orderBy" placeholder="排序字段" style="width: 120px">
              <el-option label="账户余额" value="balance" />
              <el-option label="开户时间" value="createTime" />
            </el-select>
            <el-select v-model="searchForm.orderType" placeholder="排序方式" style="width: 120px">
              <el-option label="升序" value="asc" />
              <el-option label="降序" value="desc" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="success" @click="openCreateDialog">开设账户</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 账户列表 -->
    <el-card class="list-card">
      <el-table :data="accountList" style="width: 100%" v-loading="loading">
        <el-table-column prop="accountNo" label="账户号" width="180" />
        <el-table-column prop="accountName" label="开户人" width="120" />
        <el-table-column prop="balance" label="账户余额">
          <template #default="scope">
            {{ formatMoney(scope.row.balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="accountType" label="账户类型" width="100">
          <template #default="scope">
            <el-tag type="info">
              {{ getAccountTypeName(scope.row.accountType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="账户状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '冻结' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bankName" label="银行名称" width="150" />
        <el-table-column prop="bankAddress" label="银行地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="openTime" label="开户时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.status === 1" type="primary" size="small" @click="handleDeposit(scope.row)">存入</el-button>
            <el-button v-if="scope.row.status === 1" type="warning" size="small" @click="handleWithdraw(scope.row)">支取</el-button>
            <el-button type="danger" size="small" @click="handleFreeze(scope.row)">
              {{ scope.row.status === 1 ? '冻结' : '解冻' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 开设账户对话框 -->
    <el-dialog v-model="createDialogVisible" title="开设账户" width="500px">
      <el-form :model="createForm" :rules="rules" ref="createFormRef" label-width="100px">
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="createForm.accountName" placeholder="自动生成账户名称" readonly />
        </el-form-item>
        <el-form-item label="账户类型" prop="accountType">
          <el-select v-model="createForm.accountType" placeholder="请选择账户类型" style="width: 100%">
            <el-option label="个人账户" :value="1" />
            <el-option label="企业账户" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户ID" prop="custId">
          <el-input v-model="createForm.custId" placeholder="自动生成客户ID" readonly />
        </el-form-item>
        <el-form-item label="初始金额" prop="initialAmount">
          <el-input-number v-model="createForm.initialAmount" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-input v-model="createForm.bankName" placeholder="请输入银行名称" />
        </el-form-item>
        <el-form-item label="银行地址" prop="bankAddress">
          <el-input v-model="createForm.bankAddress" placeholder="请输入银行地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="createForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateAccount">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 存取款对话框 -->
    <el-dialog v-model="transactionDialogVisible" :title="transactionType === 'deposit' ? '存入' : '支取'" width="400px">
      <el-form :model="transactionForm" :rules="transactionRules" ref="transactionFormRef" label-width="100px">
        <el-form-item :label="transactionType === 'deposit' ? '存入金额' : '支取金额'" prop="amount">
          <el-input-number v-model="transactionForm.amount" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="transactionForm.remark" type="textarea" :rows="3" placeholder="请输入交易备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transactionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTransaction">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { accountApi } from '@/api/account'

export default {
  name: 'AccountManagement',
  setup() {
    // 搜索表单数据
    const searchForm = reactive({
      accountNo: '',
      accountName: '',
      accountType: '',
      status: '',
      orderBy: '',
      orderType: 'asc'
    })

    // 创建账户表单数据
    const createForm = reactive({
      accountName: '',
      accountType: 1,
      custId: '',
      initialAmount: 0,
      bankName: '',
      bankAddress: '',
      remark: ''
    })

    // 表单校验规则
    const rules = {
      accountName: [
        // 自动生成，不需要验证
      ],
      accountType: [
        { required: true, message: '请选择账户类型', trigger: 'change' }
      ],
      custId: [
        // 自动生成，不需要验证
      ],
      initialAmount: [
        { required: true, message: '请输入初始金额', trigger: 'blur' }
      ],
      bankName: [
        { required: true, message: '请输入银行名称', trigger: 'blur' }
      ],
      bankAddress: [
        { required: true, message: '请输入银行地址', trigger: 'blur' }
      ]
    }

    // 交易表单数据和规则
    const transactionForm = reactive({
      accountNo: '',
      amount: 0,
      remark: ''
    })

    const transactionRules = {
      amount: [
        { required: true, message: '请输入金额', trigger: 'blur' }
      ],
      remark: [
        { required: true, message: '请输入交易备注', trigger: 'blur' }
      ]
    }

    // 列表数据
    const accountList = ref([])
    
    // 当前操作的账户
    const currentAccount = ref(null)

    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const loading = ref(false)

    // 对话框显示控制
    const createDialogVisible = ref(false)
    const transactionDialogVisible = ref(false)
    const transactionType = ref('deposit')
    
    // 表单引用
    const createFormRef = ref(null)
    const transactionFormRef = ref(null)

    // 获取账户列表
    const fetchAccountList = async () => {
      loading.value = true
      try {
        // 构建请求参数
        const params = {
          page: currentPage.value,
          size: pageSize.value
        }
        
        // 添加非空搜索条件
        if (searchForm.accountNo) params.accountNo = searchForm.accountNo
        if (searchForm.accountName) params.accountName = searchForm.accountName
        if (searchForm.accountType) params.accountType = searchForm.accountType
        if (searchForm.status) params.status = searchForm.status
        
        // 添加非空排序条件
        if (searchForm.orderBy) {
          params.orderBy = searchForm.orderBy
          params.orderType = searchForm.orderType || 'asc'
        }
        
        const res = await accountApi.getList(params)
        if (res.code === "200" && res.data) {
          // 新的API返回格式: res.data.records 包含记录列表, res.data.total 包含总记录数
          accountList.value = res.data.records || []
          total.value = res.data.total || 0
          currentPage.value = res.data.current || 1
          pageSize.value = res.data.size || 10
        } else {
          ElMessage.error(res.msg || '获取账户列表失败')
        }
      } catch (error) {
        console.error('获取账户列表失败:', error)
        ElMessage.error('获取账户列表失败')
      } finally {
        loading.value = false
      }
    }

    // 方法定义
    const handleSearch = () => {
      currentPage.value = 1
      fetchAccountList()
    }

    // 生成8位随机数字
    const generateRandomNumber = (length) => {
      let result = '';
      for (let i = 0; i < length; i++) {
        result += Math.floor(Math.random() * 10);
      }
      return result;
    }

    const openCreateDialog = () => {
      // 自动生成账户名称和客户ID
      createForm.accountName = 'AC' + generateRandomNumber(8);
      createForm.accountType = 1;
      createForm.custId = generateRandomNumber(12);
      createForm.initialAmount = 0;
      createForm.bankName = '';
      createForm.bankAddress = '';
      createForm.remark = '';
      createDialogVisible.value = true;
    }

    const handleCreateAccount = async () => {
      if (!createFormRef.value) return
      
      try {
        await createFormRef.value.validate()
        loading.value = true
        
        // 确保使用自动生成的值
        if (!createForm.accountName.startsWith('AC') || createForm.accountName.length !== 10) {
          createForm.accountName = 'AC' + generateRandomNumber(8);
        }
        
        if (createForm.custId.length !== 12) {
          createForm.custId = generateRandomNumber(12);
        }
        
        const res = await accountApi.create(createForm)
        if (res.code === "200") {
          ElMessage.success('开户成功')
          createDialogVisible.value = false
          fetchAccountList()
        } else {
          ElMessage.error(res.msg || '开户失败')
        }
      } catch (error) {
        console.error('开户失败:', error)
        ElMessage.error('开户失败')
      } finally {
        loading.value = false
      }
    }

    const handleDeposit = (row) => {
      transactionType.value = 'deposit'
      currentAccount.value = row
      transactionForm.accountNo = row.accountNo
      transactionForm.amount = 0
      transactionForm.remark = ''
      transactionDialogVisible.value = true
    }

    const handleWithdraw = (row) => {
      transactionType.value = 'withdraw'
      currentAccount.value = row
      transactionForm.accountNo = row.accountNo
      transactionForm.amount = 0
      transactionForm.remark = ''
      transactionDialogVisible.value = true
    }

    const handleTransaction = async () => {
      if (!transactionFormRef.value) return
      
      try {
        await transactionFormRef.value.validate()
        loading.value = true
        
        let res
        if (transactionType.value === 'deposit') {
          // 存款接口使用accountId
          const depositParams = {
            accountId: Number(currentAccount.value.accountId),
            amount: transactionForm.amount,
            remark: transactionForm.remark
          }
          res = await accountApi.deposit(depositParams)
        } else {
          // 取款接口也使用accountId
          const withdrawParams = {
            accountId: Number(currentAccount.value.accountId),
            amount: transactionForm.amount,
            remark: transactionForm.remark
          }
          res = await accountApi.withdraw(withdrawParams)
        }
        
        if (res.code === "200") {
          ElMessage.success(transactionType.value === 'deposit' ? '存款成功' : '取款成功')
          transactionDialogVisible.value = false
          fetchAccountList()
        } else {
          ElMessage.error(res.msg || (transactionType.value === 'deposit' ? '存款失败' : '取款失败'))
        }
      } catch (error) {
        console.error(transactionType.value === 'deposit' ? '存款失败' : '取款失败', error)
        ElMessage.error(transactionType.value === 'deposit' ? '存款失败' : '取款失败')
      } finally {
        loading.value = false
      }
    }

    const handleFreeze = (row) => {
      const isFreeze = row.status === 1
      const action = isFreeze ? '冻结' : '解冻'
      
      // 先让用户输入备注
      ElMessageBox.prompt(
        `请输入${action}原因`,
        `${action}账户`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: `请输入${action}原因`,
          inputValidator: (value) => {
            if (!value) {
              return `${action}原因不能为空`
            }
            return true
          },
          type: 'warning'
        }
      ).then(async ({ value: remark }) => {
        try {
          loading.value = true
          
          let res
          const accountId = row.accountId
          
          if (isFreeze) {
            // 冻结账户
            res = await accountApi.freeze(accountId, remark)
          } else {
            // 解冻账户
            res = await accountApi.unfreeze(accountId, remark)
          }
          
          if (res.code === "200") {
            ElMessage.success(`${action}成功`)
            fetchAccountList()
          } else {
            ElMessage.error(res.msg || `${action}失败`)
          }
        } catch (error) {
          console.error(`${action}失败:`, error)
          ElMessage.error(`${action}失败`)
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    }

    const formatMoney = (value) => {
      return `¥ ${Number(value).toFixed(2)}`
    }

    const getAccountTypeName = (type) => {
      const types = {
        1: '个人账户',
        2: '企业账户'
      }
      return types[type] || '未知类型'
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchAccountList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchAccountList()
    }
    
    // 初始加载数据
    onMounted(() => {
      fetchAccountList()
    })

    return {
      searchForm,
      createForm,
      rules,
      transactionForm,
      transactionRules,
      accountList,
      currentPage,
      pageSize,
      total,
      loading,
      createDialogVisible,
      transactionDialogVisible,
      transactionType,
      createFormRef,
      transactionFormRef,
      handleSearch,
      openCreateDialog,
      handleCreateAccount,
      handleDeposit,
      handleWithdraw,
      handleTransaction,
      handleFreeze,
      formatMoney,
      getAccountTypeName,
      handleSizeChange,
      handleCurrentChange,
      generateRandomNumber
    }
  }
}
</script>

<style scoped>
.account-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
}
</style> 